package com.zsh.admin.controller;

import com.zsh.admin.bean.Account;
import com.zsh.admin.bean.User;
import com.zsh.admin.service.AccountService;
import com.zsh.admin.service.UserService;
import com.zsh.admin.service.impl.AccountServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author zsh
 * @Description
 * @create 2022-02-25 15:25
 */
@Controller
public class IndexController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    AccountService accountService;



    @ResponseBody
    @GetMapping("/acct")
    public Account getById(@RequestParam("id")Integer id){

        return accountService.getAccountById(id);
    }

    @ResponseBody
    @GetMapping("/sql")
    public String queryFromDb(){
        String sql = "select count(*) from t_account";
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        Long aLong = jdbcTemplate.queryForObject(sql, Long.class);
        return aLong.toString();
    }

    /**
     * 登录页
     * @return
     */
    @GetMapping(value = {"/","/login"})
    public String loginPage(){
        return "login";
    }

    @PostMapping("/login")
    public String mainPage(User user, HttpSession session, Model model){

        if (!user.getUsername().isEmpty() && !user.getPassword().isEmpty()){
            //登录成功的用户
            session.setAttribute("loginUser",user);
            System.out.println(user);
            //登录成功 重定向
            return "redirect:/main.html";
        }
        //登录成功 重定向
        model.addAttribute("msg","账号或密码错误");
        return "login";
    }

    @GetMapping("/main.html")
    public String main(HttpSession session,Model model){
        //是否登录 使用拦截器或过滤器机制进行判断
        Object loginUser = session.getAttribute("loginUser");
        if (null != loginUser){
            return "main";
        } else {
            model.addAttribute("msg","请先登录");
            return "login";
        }


    }
}
